// 获取指定form中的所有的<input><select>对象
function getElements(formId) {
  const form = document.getElementById(formId);
  if(form == null){
    return false;
  }
  let elements = [];
  const inputTagElements = form.getElementsByTagName('input');
  for (let j = 0; j < inputTagElements.length; j++) {
    elements.push(inputTagElements[j]);
  }

  const selectTagElements = form.getElementsByTagName('select');
  for (let j = 0; j < selectTagElements.length; j++) {
    elements.push(selectTagElements[j]);
  }

  const textareaTagElements = form.getElementsByTagName('textarea');
  for (let j = 0; j < textareaTagElements.length; j++) {
    elements.push(textareaTagElements[j]);
  }
  return elements;
}

// 获取单个input中的【name,value】数组
function inputSelector(element) {
  if (element.checked)
    return [ element.name, element.value ];
}

function selectOne(element) {
  if(element.value !== ""){
    let name = element.name;
    return [name, element.value ];
  }
}
function textarea(element) {
  if(element.value !== ""){
    let name = element.name;
    return [name, element.value ];
  }
}

function input(element) {
  switch (element.type.toLowerCase()) {
    case 'hidden':
    case 'password':
    case 'text':
      return [ element.name, element.value ];
    case 'checkbox':
    case 'radio':
      return inputSelector(element);
    case 'select-one':
      return selectOne(element);
    case 'textarea':
      return textarea(element);
  }
  return false;
}

// 组合URL
function serializeElement(element) {
  let method = element.tagName.toLowerCase();
  // console.log(method)
  let parameter = input(element);
  if (parameter) {
    console.log(parameter, parameter[1]);
    let key = parameter[0];
    if (key.length === 0)
      return;
    if (parameter[1].constructor !== Array)
      parameter[1] = [ parameter[1] ];

    let values = parameter[1];
    let results = [];
    for (let i = 0; i < values.length; i++) {
      results.push(`"${key}": "${values[i]}"`);
    }
    return results.join();
  }
}

// 调用方法
function serializeForm(formId) {
  let elements = getElements(formId);
  let queryComponents = new Array();

  for (let i = 0; i < elements.length; i++) {
    let queryComponent = serializeElement(elements[i]);
    if (queryComponent)
      queryComponents.push(queryComponent);
  }
  return `{${queryComponents.join(',')}}`;
}